package gold.digger;

import gold.utils.InputUtil;

import java.util.*;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC632 {
    public long startExecuteTime = System.currentTimeMillis();


    /*
     * @param 此题目参考了别人代码
     * 这是因为问题情况较为复杂
     * 未来需要再次复习此道题目
     * @return:
     */
    class Solution {
        public int[] smallestRange(List<List<Integer>> nums) {
            int N = 0;
            for (List<Integer> num : nums) N += num.size();
            int[][] ordered = new int[N][2];
            int i = 0;
            int j = 0;
            for (List<Integer> group : nums) {
                for (Integer num : group) {
                    ordered[i][0] = num;
                    ordered[i][1] = j;
                    i++;
                }
                j++;
            }
            Arrays.sort(ordered, (o1, o2) -> (o1[0] - o2[0]));
            int[] ans = new int[2];
            int[] count = new int[nums.size()];
            int k = 0;
            i = 0;
            for (j = 0; j < N; j++) {
                if (0 == count[ordered[j][1]]++) k++;
                if (k == nums.size()) {
                    while (count[ordered[i][1]] > 1) count[ordered[i++][1]]--;
                    if ((ans[0] == 0 && ans[1] == 0) || ans[1] - ans[0] > ordered[j][0] - ordered[i][0]) {
                        ans = new int[]{ordered[i][0], ordered[j][0]};
                    }
                }
            }
            return ans;
        }
    }

    public void run() {
        Solution solution = new Solution();
        List<List<Integer>> lists = InputUtil.toDoubleIntegerList("[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]]");
        System.out.println(solution.smallestRange(lists));
    }

    public static void main(String[] args) throws Exception {
        LC632 an = new LC632();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
